package com.laikan.reader.bookfriend.activity;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.FeedBackAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.FeedBackBean;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 意见反馈
 *
 * @author wxl
 */
public class FeedBackActivity extends BasicActivity implements OnClickListener {

    private EditText feed_edit;
    private TextView send_btn;
    private ListView feedback_list;
    private FeedBackAdapter mAdapter;
    private ArrayList<FeedBackBean> mData;
    private String content;
    private String version;
    private ImageView back_tv;
    Drawable drawable_back_tv;
    private RelativeLayout back_layout;
    private LoadingDialog mloadingDialog;

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.feedback);
        feed_edit = (EditText)findViewById(R.id.et_feed);
        send_btn = (TextView)findViewById(R.id.btn_send);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        feedback_list = (ListView)findViewById(R.id.feedback_list);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
    }

    @Override
    protected void initData() {
        mloadingDialog = new LoadingDialog(mContext);
        mData = new ArrayList<FeedBackBean>();
        mAdapter = new FeedBackAdapter(mContext, mData);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        getData();
        feedback_list.setAdapter(mAdapter);
        version = getIntent().getStringExtra("version");
    }

    /**
     * 获取反馈数据
     */
    private void getData() {
        mloadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mloadingDialog.dismiss();
                BaseDataBean<BaseListDataBean<FeedBackBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<FeedBackBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
                if (result != null) {
                    if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {

                        ToastMgr.showShortToast(result.getError_msg());
                    }else {
                        mData = result.getData().getData();
                        mAdapter.setDatas(mData);
                    }
                }else {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。16");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_feedback);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_feedback, map, null, null, requestListener);
    }

    @Override
    protected void setListener() {
        send_btn.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        feed_edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(feed_edit.getWindowToken(), 0);
                }
            }
        });
        feed_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                content = feed_edit.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    send_btn.setTextColor(getResources().getColor(R.color.C_66ccdd));
                }else {
                    send_btn.setTextColor(getResources().getColor(R.color.C_333333));
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_send:
                if (feed_edit.getText().toString().trim().length() == 0) {
                    ToastMgr.showShortToast(R.string.laikan_empty_content_toast);
                    return;
                }
                send();
                break;
            case R.id.back_layout:
                feed_edit.clearFocus();
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 发送反馈数据
     */
    private void send() {
        mloadingDialog.show();
        content = feed_edit.getText().toString().trim();
        Map<String, String> map = new HashMap<>();
        map.put("uid", SPUtil.getString("user_id", ""));
        map.put("token", SPUtil.getString("token", ""));
        map.put("version", version);
        map.put("content", content);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mloadingDialog.dismiss();
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        ToastMgr.showShortToast(R.string.feedback_success);
                        getData();
                        feed_edit.setText("");
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }
                }catch (JSONException e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。17");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_add_feedback);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_add_feedback, map, null, null, requestListener);
    }

}
